package cn.kdyzm.twofa.service.impl;

import cn.kdyzm.json.util.JsonUtils;
import cn.kdyzm.twofa.entity.SysUser;
import cn.kdyzm.twofa.entity.SysUser2fa;
import cn.kdyzm.twofa.mapper.ISysUser2faMapper;
import cn.kdyzm.twofa.mapper.ISysUserMapper;
import cn.kdyzm.twofa.service.ISysUser2faService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.warrenstrange.googleauth.ICredentialRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author kdyzm
 * @date 2025/6/16
 */
@Slf4j
@Service
@AllArgsConstructor
public class ICredentialRepositoryImpl implements ICredentialRepository {

    private final ISysUserMapper sysUserMapper;

    private final ISysUser2faMapper sysUser2faMapper;

    private final ISysUser2faService sysUser2faService;

    @Override
    public String getSecretKey(String userName) {
        SysUser sysUserByUserName = sysUserMapper.getSysUserByUserName(userName);
        return sysUserByUserName.getTwoFaSecret();
    }

    @Override
    public void saveUserCredentials(String userName,
                                    String secretKey,
                                    int validationCode,
                                    List<Integer> scratchCodes) {
        SysUser sysUser = sysUserMapper.getSysUserByUserName(userName);
        Long userId = sysUser.getId();
        SysUser2fa sysUser2fa = new SysUser2fa();
        sysUser2fa.setUserId(userId);
        sysUser2fa.setSecretKey(secretKey);
        sysUser2fa.setScratchCodes(JsonUtils.toString(scratchCodes));
        sysUser2fa.setCreateBy("sys");
        sysUser2faService.saveOrUpdate(sysUser2fa,
                new LambdaQueryWrapper<SysUser2fa>()
                        .eq(SysUser2fa::getUserId, userId)
        );

    }
}
